import requests
from lxml import etree

from ddddocr import DdddOcr
import time
ocr = DdddOcr(show_ad=False)

t=int(time.time()*1000)


# 1. 获取隐藏域
res_login_get = requests.get('https://www.gushiwen.cn/user/login.aspx')
tree = etree.HTML(res_login_get.text)


__VIEWSTATE = tree.xpath('//input[@id="__VIEWSTATE"]/@value')[0]
__VIEWSTATEGENERATOR = tree.xpath('//input[@id="__VIEWSTATEGENERATOR"]/@value')[0]




while True:
    # 2. 解析验证码
    res_img = requests.get(f'https://www.gushiwen.cn/RandCode.ashx?t={t}')

    # print(res.content)
    with open(f'./tu/yzm/yy.jpg', 'wb') as f:
        f.write(res_img.content)

    r = ocr.classification(res_img.content)
    print(f"识别结果 {r}")
    print(type(res_img.cookies))

    # 3. 发起登录请求
    res_login_post = requests.post('https://www.gushiwen.cn/user/login.aspx', data={
        '__VIEWSTATE': __VIEWSTATE,
        '__VIEWSTATEGENERATOR': __VIEWSTATEGENERATOR,
        'email': '1375395139@qq.com',
        'pwd': '123456',
        'denglu': '登录',
        'code': f'{r}'
    }, cookies=res_img.cookies)   # 携带cookie 是为了携带验证码 对应的cookie codeyz

    if "您输入的验证码有误" in res_login_post.text:
        print(f"验证码识别失败， 刷新验证码再次识别 ")
    else:
        break


print(res_login_post.cookies)

res_collect = requests.get('https://www.gushiwen.cn/user/collect.aspx', cookies=res_login_post.cookies)

tree = etree.HTML(res_collect.text)

items = tree.xpath('//div[@class="sons"]/div[@class="cont"]/a')
for item in items:
    print(item.xpath('./@href'), item.xpath('./text()'))